import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 后端返回的路由和前端注册的路由，选择的拼接
 * @param from 后端返回的路由的数组，
 * @param target 前端定义的路由，循环之后的对象
 * @param ret 整合完的数组
 */
function selectRoutes(from, target, ret = []) {
  from.forEach((item, index) => {
    const path = item.path
    let child = target[index] || {}

    target.forEach((tar_item) => {
      if (tar_item.path === path) {
        child = { ...tar_item }
      }
    })

    // 如果没有这个对象，或者这个对象的path !== 这后端返回的path。直接结束
    if (!child || child.path !== path) {
      return
    }

    ret[index] = { ...child }

    delete ret[index].children

    // 后端返回，和前端都有子集的
    if ((item.children && item.children.length) && (child.children && child.children.length)) {
      const childClonedList = selectRoutes(item.children, child.children)

      if (childClonedList.length) {
        ret[index].children = childClonedList
      }
    }

    // 后端返回没子集，前端有子集 && 子集的第一个的path必须等于 'index'
    if (!(item.children && item.children.length) && (child.children && child.children.length && child.children[0].path === 'index')) {
      ret[index].children = child.children
    }
  })

  return ret
}

const notPage = { path: '*', redirect: '/404', hidden: true }

const state = {
  routes: [], // 前端默认显示，和后端返回的结合路由
  addRoutes: [] // 后端返回的需要显示的路由（用于router的添加）
}

const mutations = {
  // 设置路由
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 添加路由
  addRoutes({ commit }, route_list) {
    return new Promise(resolve => {
      let arr = selectRoutes(route_list, asyncRoutes)
      arr.push(notPage)
      commit('SET_ROUTES', arr)
      resolve(arr)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
